<template>
  <div class="login">
    <input
      v-model="userName"
      type="text"
      placeholder="请输入您的用户名"
      @keydown="handleKeyDown"
    />
    <button v-on:click="handleClickBtn">登录</button>
  </div>
</template>

<script>
export default {
  name: "Login",

  data() {
    return {
      testName: "test",
      userName: "",
      storage: localStorage,
    };
  },

  // 组件被创建前端执行
  created() {
    // console.log(this.$router);
    // console.log(this.$route);
    console.log("created testName", this.testName);
    this.autoLogin();
  },

  methods: {
    // 自动登录
    autoLogin() {
      if (this.storage.getItem("userName")) {
        this.gotoHome();
      }
    },

    // 处理按钮点击事件
    handleClickBtn() {
      const userName = this.userName.trim();
      if (!this.checkoutUserName(userName)) {
        alert("用户名长度不能低于 3 位哦");
        return;
      }
      this.storage.setItem("userName", userName);
      this.userName = "";
      this.gotoHome();
    },

    // 处理键盘事件
    handleKeyDown(event) {
      // console.log(event);
      if (event.key === "Enter") {
        this.handleClickBtn();
      }
    },

    // 用户名校验
    checkoutUserName(userName) {
      return userName.length > 3 ? true : false;
    },

    // 去首页
    gotoHome() {
      this.$router.push("/home");
    },
  },

  test() {
    console.log("test", this);
    // console.log("test data", this.data);
    console.log("test testName", this.testName);
  },
};
</script>
